import axios from "axios";
import { message } from "antd";

const baseURL = import.meta.env.VITE_APP_BASE_API as string;
const service = axios.create({
  baseURL,
  timeout: 3000,
  timeoutErrorMessage: "请求超时,请刷新再试",
  withCredentials: true,
  headers: {
    "Content-Type": "application/json",
    Authorization: "Bearer " + localStorage.getItem("token") || "",
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use((response) => {
  const data = response.data;
  if (data.code !== 200) {
    message.error(data.message);
    return Promise.reject(data);
  }
  return data.data;
});

export default {
  get<T>(url: string, params?: object): Promise<T> {
    return service.get(url, { params });
  },
  post<T>(url: string, data?: object): Promise<T> {
    return service.post(url, data);
  },
  put<T>(url: string, data?: object): Promise<T> {
    return service.put(url, data);
  },
  delete<T>(url: string, params?: object): Promise<T> {
    return service.delete(url, { params });
  },
};
